package com.wang.tool.common.result;

import com.wang.tool.common.Pair;
import com.wang.tool.common.SimpleException;
import com.wang.tool.util.CommonUtil;

import java.io.Serializable;
import java.util.*;

/**
 * 批量结果
 * 结果解析示例
 * <p>
 * Pair firstFail = result.findFirstFail();
 * if(firstFail!=null){
 * //有失败的
 * } else if(!result.isSuccess){
 * //整体失败
 * }else{
 * //成功
 * }
 *
 * @author shaopeng
 * @date 2023/5/23
 */
public class BatchResult<T, P extends Serializable> extends BaseResult {

    private static final long serialVersionUID = -7564202278110846961L;

    /**
     * 成功的结果
     */
    private List<T> successes;

    /**
     * 异常的参数及原因
     */
    private LinkedHashMap<P, String> fails;

    /**
     * 添加成功实体
     *
     * @param successEntity
     */
    public synchronized void addSuccessEntity(T successEntity) {
        if (successEntity == null) {
            return;
        }
        successes = successes == null ? new ArrayList<>() : successes;
        successes.add(successEntity);
    }


    /**
     * 添加失败部分
     *
     * @param part
     * @param errorMsg
     */
    public synchronized void addFailPart(P part, String errorMsg) {
        if (part == null) {
            return;
        }
        fails = fails == null ? new LinkedHashMap<>() : fails;
        fails.put(part, errorMsg == null ? SimpleException.UNKNOWN_ERROR : errorMsg);
    }


    /**
     * 寻找第一个失败的部分
     * left:失败的部分，right:失败的原因
     *
     * @return
     */
    public Pair<P, String> findFirstFail() {
        if (CommonUtil.isEmpty(fails)) {
            return null;
        }
        Iterator<Map.Entry<P, String>> iterator = fails.entrySet().iterator();
        Map.Entry<P, String> next = iterator.next();
        return new Pair<>(next.getKey(), next.getValue());
    }

    /**
     * 寻找第一个成功的
     *
     * @return
     */
    public T findFirstSuccess() {
        if (CommonUtil.isEmpty(successes)) {
            return null;
        }
        return successes.get(0);
    }


    public List<T> getSuccesses() {
        return successes;
    }

    public void setSuccesses(List<T> successes) {
        this.successes = successes;
    }

    public LinkedHashMap<P, String> getFails() {
        return fails;
    }

    public void setFails(LinkedHashMap<P, String> fails) {
        this.fails = fails;
    }
}
